﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using System.IO;
using System.Xml.Linq;
using System.Windows.Media.Imaging;
using System.Windows.Data;
using Microsoft.Phone.Shell;

namespace ByrForum
{
    
    public partial class PanoramaMainPage : PhoneApplicationPage
    {
        List<ArticleInfo> articlelist = new List<ArticleInfo>();
        List<ArticleInfo> focusArticleList = new List<ArticleInfo>();
        List<ArticleInfo> hotArticleList = new List<ArticleInfo>();
        bool focusLoad = false;
        bool hotLoad = false;
        bool topLoad = false;
        int currentTabIndex = 0;

        public PanoramaMainPage()
        {
            InitializeComponent();

            txtAstro.Text = App.MyInfo.astro;
            txtGender.Text = App.MyInfo.gender;
            txtLife.Text = App.MyInfo.life;
            txtPostCount.Text = App.MyInfo.post_count;
            txtScore.Text = App.MyInfo.score;
            txtUserid.Text = App.MyInfo.id;
            txtUsername.Text = App.MyInfo.user_name;
            Test t;
            t = new Test() { Image = App.MyInfo.face_url};
            imgUser.DataContext = t;
            //this.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(PanoramaMainPage_BackKeyPress);
            String myRequestUrl = ByrApi.apiUrl + ByrApi.topten + ByrApi.Encode + ByrApi.appkey;
            RequestState state = new RequestState();
            state.listbox = listbox;
            state.articlelist = articlelist;
            HttpUtil.HttpGetWithParam(state,myRequestUrl, HttpWebRequset_Callback);
            this.progressBarWait.Visibility = Visibility.Visible;

        }

        void PanoramaMainPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("确定退出程序？", "退出", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
            {
                e.Cancel = true;
                return;
            }
            while (NavigationService.BackStack.Any())
                NavigationService.RemoveBackEntry();
            this.IsHitTestVisible = this.IsEnabled = false;
            if (this.ApplicationBar != null)
            {
                foreach (var item in this.ApplicationBar.Buttons.OfType<ApplicationBarIconButton>())
                {
                    item.IsEnabled = false;
                }
            }
            
            
            //base.OnBackKeyPress(e);
        }


        private void HttpWebRequset_Callback(IAsyncResult asynchronousResult)
        {
            RequestState state = (RequestState)asynchronousResult.AsyncState;
            ListBox call_listbox = state.listbox;
            List<ArticleInfo> call_articleList = state.articlelist;

            try
            {
                string result = HttpUtil.ReadToEndWithParam(asynchronousResult);
                DebugInfo.writeXml(result);
                XDocument doc = XDocument.Parse(result);
                Debug.WriteLine(((XElement)doc.FirstNode).Name);
                foreach (XElement item in doc.Descendants("widget").Nodes())
                {
                    if (item.Name.ToString() == "article")
                    {
                        foreach (XElement articleitem in item.Elements())
                        {
                            string title = "";
                            string info = "";
                            string group_id = "";
                            foreach (XElement childitem in articleitem.Elements())
                            {
                                if (childitem.Name == "board_name")
                                    info = childitem.Value;
                                if (childitem.Name == "title")
                                    title = childitem.Value;
                                if (childitem.Name == "group_id")
                                {
                                    group_id = childitem.Value;
                                }
                            }
                            this.Dispatcher.BeginInvoke(
                                () =>
                                {
                                    call_listbox.Items.Add(new ItemData(title, "来自：" + info));
                                    
                                }
                                );
                            call_articleList.Add(new ArticleInfo(info, group_id, title, ""));
                            
                            Debug.WriteLine(title + info);

                        }
                    }

                }
                this.Dispatcher.BeginInvoke(
                        () => {
                            this.progressBarWait.Visibility = Visibility.Collapsed;
                            this.progressBarWaitFocus .Visibility = Visibility.Collapsed;
                            this.progressBarWaitHot.Visibility = Visibility.Collapsed;
                            switch (currentTabIndex)
                            {
                                case 0:
                                    topLoad=true;;
                                    threeItemTab.IsEnabled = true;
                                    break;
                                case 1:
                                    focusLoad=true;;
                                    threeItemTab.IsEnabled = true;
                                    break;
                                case 2:
                                    hotLoad=true;;
                                    threeItemTab.IsEnabled = true;
                                    break;
                                default:
                                    break;
                            }
                        }
                    );
                

            }
            catch(Exception ee)
            {
                Debug.WriteLine("get callback failed");
                Debug.WriteLine(ee.Message);
                this.Dispatcher.BeginInvoke(
                        () =>
                        {
                            MessageBox.Show("网络错误");
                            this.progressBarWait.Visibility = Visibility.Collapsed;
                            this.progressBarWaitFocus.Visibility = Visibility.Collapsed;
                            this.progressBarWaitHot.Visibility = Visibility.Collapsed;
                        }
                    );
            }
        }

        private void OnListItemSelected(object sender, SelectionChangedEventArgs e)
        {
          
        }

        private void listbox_KeyUp(object sender, KeyEventArgs e)
        {
            
        }

        private void listbox_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if ((((ListBox)sender).SelectedIndex == -1)) return;
            this.NavigationService.Navigate(new Uri("/TopTen.xaml?board=" + articlelist[((ListBox)sender).SelectedIndex].Board
                + "&group_id=" + articlelist[((ListBox)sender).SelectedIndex].Group_id
                + "&title=" + articlelist[((ListBox)sender).SelectedIndex].Title, UriKind.Relative));
        }

        private void listboxBoard_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            
            this.NavigationService.Navigate(new Uri("/BoardList.xaml?title="+((ListBox)sender).SelectedIndex.ToString(),UriKind.Relative));
        }

        private void MainPageTabControl_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            currentTabIndex = MainPageTabControl.SelectedIndex;
            String myRequestUrl;
            switch (MainPageTabControl.SelectedIndex)
            { 
                case 1:
                    if (!focusLoad)
                    {
                        myRequestUrl = ByrApi.apiUrl + ByrApi.focus + ByrApi.Encode + ByrApi.appkey;
                        RequestState state = new RequestState();
                        state.listbox = listboxFocus;
                        state.articlelist = focusArticleList;
                        HttpUtil.HttpGetWithParam(state, myRequestUrl, HttpWebRequset_Callback);
                        //HttpUtil.HttpGet(myRequestUrl, HttpWebRequset_Callback);
                        this.progressBarWaitFocus.Visibility = Visibility.Visible;
                        focusLoad = true;
                    }
                    
                    break;
                case 2:
                    if (!hotLoad)
                    {
                        myRequestUrl = ByrApi.apiUrl + ByrApi.recommend + ByrApi.Encode + ByrApi.appkey;
                        RequestState state = new RequestState();
                        state.listbox = listboxHot;
                        state.articlelist =hotArticleList;
                        HttpUtil.HttpGetWithParam(state, myRequestUrl, HttpWebRequset_Callback);
                        //HttpUtil.HttpGet(myRequestUrl, HttpWebRequset_Callback);
                        this.progressBarWaitHot.Visibility = Visibility.Visible;
                        hotLoad = true;
                    }
                    break;
                default:
                    break;

            }

        }

        private void listboxFocus_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (!focusLoad ||(((ListBox)sender).SelectedIndex==-1))
                return;
            this.NavigationService.Navigate(new Uri("/TopTen.xaml?board=" + focusArticleList[((ListBox)sender).SelectedIndex].Board
                + "&group_id=" + focusArticleList[((ListBox)sender).SelectedIndex].Group_id
                + "&title=" + focusArticleList[((ListBox)sender).SelectedIndex].Title, UriKind.Relative));

        }

        private void listboxHot_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (!hotLoad || (((ListBox)sender).SelectedIndex == -1))
                return;
            this.NavigationService.Navigate(new Uri("/TopTen.xaml?board=" + hotArticleList[((ListBox)sender).SelectedIndex].Board
                + "&group_id=" + hotArticleList[((ListBox)sender).SelectedIndex].Group_id
                + "&title=" + hotArticleList[((ListBox)sender).SelectedIndex].Title, UriKind.Relative));
        }
    }
    public class ItemData
    {
        public ItemData(string title, string info)
        {
            ArticleTitle = title;
            ArticleInfo = info;
        }
        public string ArticleTitle { get; set; }
        public string ArticleInfo { get; set; }
    }
    public class Test { public string Image { set; get; } } 
}